package com.ys.utils.base.http;

import com.alibaba.fastjson.JSON;
import com.ys.base.EnumType;
import com.ys.utils.base.j2se.JsonUtil;
import com.ys.utils.base.j2se.Logger;
import com.ys.utils.base.j2se.MapHandler;
import com.ys.utils.base.j2se.StringHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Description
 * Created by dhf
 * Date create on 17:52 2019/11/19.
 */
public class ResponseHandler {

    /**
     * 业务成功 没有返回信息
     */
    public static String success() {
        return result("0", "操作成功", null);
    }

    /**
     * 业务成功 data是返回信息 必须是map或object
     * 不能是list list用下面的方法 map的key默认为list
     */
    public static String success(Object data) {
        if (data instanceof List<?>) {
            throw new RuntimeException("返回信息不能为list");
        }
        return result("0", "操作成功", data);
    }

    public static String success(String code, Object data) {
        if (data instanceof List<?>) {
            throw new RuntimeException("返回信息不能为list");
        }
        return result(code, "操作成功", data);
    }

    /**
     * 业务成功 返回data的key是list value是list
     */
    public static String list(List<?> list) {
        return result("0", "操作成功", MapHandler.getMap("list", list));
    }

    /**
     * 业务出错
     *
     * @param code 错误码
     * @param msg  错误消息
     */
    public static String error(String code, String msg) {
        return result(code, msg, null);
    }

    /**
     * 业务出错
     */
    public static String error(EnumType.ResponseCode code) {
        return result(code.getCode(), code.getDesc(), null);
    }

    /**
     * 业务响应
     *
     * @param code 响应码 不为0 代表错误
     * @param msg  错误信息 当出错的时候 有错误信息 前端提示
     * @param data 成功以后的业务数据 必须是map或object 不能是list
     * @return 响应结果 json串
     */
    public static String result(String code, String msg, Object data) {
        Map<String, Object> map = new HashMap<>();
        map.put("msg", msg);
        map.put("code", StringHandler.getInt(code));
        map.put("data", data);
        return JSON.toJSONString(map);
    }

    /**
     * 输出返回消息
     */
    public static void write(Map<String, Object> msg, HttpServletRequest request, HttpServletResponse response) {
        write(JsonUtil.toJson(msg), request, response);
    }

    /**
     * 输出返回消息
     */
    public static void write(String string, HttpServletRequest request, HttpServletResponse response) {
        try {
            string = string.replaceAll("[\\x00-\\x1F]", "_");
            response.setCharacterEncoding("utf-8");
            response.setContentType("application/json");
            PrintWriter writer = response.getWriter();
            writer.print(string);
            writer.flush();
            writer.close();
        } catch (IOException e) {
            Logger.error("响应助手输出返回消息", e);
        }
    }

}
